<template>
  <div>
    <div v-if="searchStatus" class="box-shadow pad10 mgb10">
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        class="fnmb talj"
        label-width="70px"
      >
        <div class="flex jbetween">
          <div>
            <el-form-item label="编号">
              <el-input
                v-model="queryParams.Code"
                placeholder="请输入"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="名称">
              <el-input
                v-model="queryParams.Name"
                placeholder="请输入"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="区域">
              <Selector
                v-model="queryParams.Area"
                @getItem="queryParams.Place = ''"
                category="学校区域"
              />
            </el-form-item>
            <el-form-item label="场地">
              <Selector
                v-model="queryParams.Place"
                :query="{
                  ID_Area: queryParams.Area
                }"
                category="全部场地"
              />
            </el-form-item>
            <el-form-item label="启用">
              <Selector v-model="queryParams.Enable" category="启用" />
            </el-form-item>
            <el-form-item label="状况" v-if="props.Category == 2">
              <Selector
                v-model="queryParams.State_Self"
                category="设备自身状态"
              />
            </el-form-item>
            <el-form-item label="过程状态">
              <Selector
                v-model="queryParams.State"
                category="设备过程状态"
                :query="{
                  Type: props.Category
                }"
              />
            </el-form-item>
          </div>
          <div class="flex acenter jend fnw">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <MyTable
      :tableList="tableList"
      :total="Total"
      :columns="columns"
      v-model:page="page"
      v-model:selectList="selectDeviceList"
      v-model:searchStatus="searchStatus"
      :btnList="$checkBtn(props.Permise.tab)"
      @link="handleDetail"
      @getList="getList"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <template v-slot:tabTop>
        <el-button
          type="primary"
          v-if="props.deviceColumns && !props.deviceColumns.length"
          v-hasPermi="props.Permise.add"
          icon="CirclePlusFilled"
          @click="handleAdd"
          >添加{{ props.Label }}</el-button
        >
        <BatchPrint :selectList="selectDevice"></BatchPrint>
      </template>
    </MyTable>
    <MyDialog
      v-model:show="show"
      :title="title"
      :formRef="formRef"
      width="80%"
      @confirm="confirm"
      :destroy="true"
    >
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form
            :model="formData"
            :rules="rules"
            inline
            ref="formRef"
            label-width="80px"
            class="wid100"
          >
            <el-row>
              <el-form-item label="展示图片">
                <FileUpload
                  :iconList="['preview', 'delete', 'setImg']"
                  type="img"
                  @getImgItem="getImgItem"
                  :detail="false"
                  v-model:fileList="fileList"
                ></FileUpload>
              </el-form-item>
            </el-row>

            <el-row>
              <MyCol>
                <el-form-item label="编号" prop="Code">
                  <el-input
                    v-model="formData.Code"
                    placeholder="请输入"
                    clearable
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="名称" prop="Name">
                  <el-input
                    v-model="formData.Name"
                    placeholder="请输入"
                    clearable
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="管理员" prop="Principal">
                  <Selector
                    category="用户列表"
                    :query="{Type:2}"
                    v-model="formData.Principal"
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="区域" prop="ID_Area">
                  <Selector
                    category="学校区域"
                    @getItem="formData.ID_Place = ''"
                    v-model="formData.ID_Area"
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="场地" prop="ID_Place">
                  <Selector
                    category="全部场地"
                    :query="{
                      ID_Area: formData.ID_Area
                    }"
                    v-model="formData.ID_Place"
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="规格型号" prop="Model">
                  <el-input
                    v-model="formData.Model"
                    placeholder="请输入"
                    clearable
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="生产厂商" prop="Manufacturer">
                  <el-input
                    v-model="formData.Manufacturer"
                    placeholder="请输入"
                    clearable
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="入厂时间" prop="FactoryTime">
                  <MyDateTime
                    format="YYYY-MM-DD"
                    v-model="formData.FactoryTime"
                    type="date"
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="类别" prop="ID_Type">
                  <Selector
                    category="设备类型"
                    :query="{
                      Category: props.Category
                    }"
                    v-model="formData.ID_Type"
                  />
                </el-form-item>
              </MyCol>
              <MyCol>
                <el-form-item label="是否启用" prop="Enable">
                  <Selector category="启用" v-model="formData.Enable" />
                </el-form-item>
              </MyCol>
              <MyCol v-if="props.Category == 2">
                <el-form-item label="状况" prop="State_Self">
                  <Selector
                    category="设备自身状态"
                    v-model="formData.State_Self"
                  />
                </el-form-item>
              </MyCol>
              <!-- <MyCol>
                <el-form-item label="过程状态" prop="State">
                  <Selector
                    category="设备过程状态"
                    :query="{ Type: props.Category }"
                    v-model="formData.State"
                  />
                </el-form-item>
              </MyCol> -->

              <MyCol>
                <el-form-item
                  label="IP地址"
                  v-if="props.Category == 1"
                  prop="IPAddress"
                >
                  <el-input
                    v-model="formData.IPAddress"
                    placeholder="请输入"
                    clearable
                  />
                </el-form-item>
              </MyCol>
            </el-row>
            <el-row>
              <el-form-item label="附件" class="fw100">
                <FileUpload
                  :detail="false"
                  v-model:fileList="fileList2"
                  :showSort="true"
                ></FileUpload>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="应用范围" prop="UseScope">
                <el-input
                  v-model="formData.UseScope"
                  placeholder="请输入"
                  clearable
                  type="textarea"
                />
              </el-form-item>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane :label="props.PlanName + '设置'" name="second">
          <el-radio-group
            v-model="checkType"
            v-if="props.Category == 2"
            @change="checkTypeChange"
          >
            <el-radio :label="1" size="large">内校</el-radio>
            <el-radio :label="2" size="large">外校</el-radio>
          </el-radio-group>

          <MyTable
            v-if="checkType == 1"
            v-model:tableList="showSelectList"
            :total="selectTotal"
            :columns="selectColumns"
            :btnList="['delete']"
            v-model:page="selectPage"
            :toolbar="false"
            :searchStatus="false"
            @delete="selectDelete"
            height="500"
          >
            <template v-slot:tabTop>
              <el-button type="primary" @click="bindExecution('绑定')"
                >绑定</el-button
              >
            </template>
          </MyTable>
          <!-- 外校 -->
          <el-table :data="outCheckList" :border="true" v-if="checkType == 2">
            <el-table-column
              prop="Interval"
              :align="'center'"
              label="时间间隔(分钟)"
              width="200px"
            >
              <template v-slot="{ row }">
                <el-input-number
                  v-model="row.Interval"
                  placeholder="请输入"
                  v-number
                  controls-position="right"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="LastMaintainTime"
              :align="'center'"
              :label="'最后一次' + props.PlanName + '时间'"
              width="300px"
            >
              <template v-slot="{ row }">
                <MyDateTime v-model="row.LastMaintainTime" />
              </template>
            </el-table-column>

            <el-table-column width="200px" :align="'center'" label="负责人">
              <template v-slot="{ row }">
                <Selector
                  category="用户列表"
                  :query="{ Type: 2 }"
                  v-model="row.Principal"
                />
              </template>
            </el-table-column>
            <el-table-column :align="'center'" label="备注">
              <template v-slot="{ row }">
                <el-input v-model="row.Remark" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column
              prop="Code"
              :align="'center'"
              label="操作"
              width="160px"
            >
              <template v-slot="{ row, $index }">
                <el-button type="text" @click="addTableData($index)">
                  <el-icon> <Plus /> </el-icon>添加
                </el-button>
                <el-button
                  @click="deleteTableData($index)"
                  v-if="$index != 0"
                  type="text"
                  style="color: red"
                >
                  <el-icon> <Delete /> </el-icon>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </MyDialog>

    <!-- 详情 -->
    <MyDialog
      v-model:show="showDetail"
      :title="props.Label + '详情'"
      :showFooter="false"
      :destroy="true"
    >
      <DeviceDetail
        @getList="getList"
        v-model:showDetail="showDetail"
        :Label="props.Label"
        :Category="props.Category"
        :detailData="detailData"
        :PlanName="props.PlanName"
      />
    </MyDialog>
    <!-- 绑定 -->
    <MyDialog
      v-model:show="bindDialog"
      :title="bindTitle"
      @confirm="subConfirm"
      :destroy="true"
    >
      <TeachMaintainPaln
        :showSet="false"
        :searchStatus="false"
        v-model:selectList="selectList"
        :Type="props.Category"
        :Label="props.Label"
      ></TeachMaintainPaln>
    </MyDialog>
  </div>
</template>

<script setup name="DeviceAccount">
import { ref, getCurrentInstance, onMounted } from 'vue';
import TeachMaintainPaln from '@/views/teachingDevice/TeachMaintainPaln/index';
import {
  GetDeviceList_Page,
  EditDevice,
  DelDevice,
  AddDevice,
  GetDeviceDetail,
  DeviceBindMaintainPlan
} from '@/api/teachDevice/account.js';
import { useRouter } from 'vue-router';
import DeviceDetail from '@/views/teachingDevice/DeviceAccount/DeviceDetail';
const emit = defineEmits(['update:checkList']);
const router = useRouter();
const props = defineProps({
  Category: {
    default: 1
  },
  Label: {
    default: '教学装备'
  },
  PlanName: {
    default: '保养'
  },
  Permise: {
    default: {
      tab: ['DeviceAccount:edit', 'DeviceAccount:delete'],
      add: ['DeviceAccount:add']
    }
  },
  deviceColumns: {
    default: []
  },
  checkList: {
    default: []
  }
});
const { proxy } = getCurrentInstance();
const tableList = ref([]);
const Total = ref(0);
const columns = ref([
  { label: '多选框' },
  { label: '序号' },
  { label: '编号', prop: 'Code', link: true, self: true },
  { label: '名称', prop: 'Name' },
  { label: '图片', prop: 'ShowPictrue', img: true },
  { label: '区域', prop: 'Area' },
  { label: '场地', prop: 'Place' },
  { label: '规格型号', prop: 'Model' },
  { label: '状况', tag: true, prop: 'State_SelfName' },
  { label: '过程状态', tag: true, prop: 'StateName' },
  { label: '类型', prop: 'Type' },
  { label: '应用范围', prop: 'Place' },
  { label: '操作', width: 200 }
]);
if (props.Category == 1) {
  columns.value = columns.value?.filter(item => item.label != '状况');
}
const outCheckList = ref([{}]);
const selectColumns = ref([
  { label: '序号' },
  { label: '编号', prop: 'Code' },
  { label: '方案名称', prop: 'Name' },
  {
    label: props.Label + '间隔(分钟)',
    prop: 'Interval',
    inputNum: true,
    width: 180
  },
  {
    label: '最后一次保养时间',
    prop: 'LastMaintainTime',
    time: true,
    width: 230
  },
  {
    label: '负责人',
    prop: 'Principal',
    select: true,
    category: '用户列表',
    query: { Type: 2 }
  },
  { label: '备注', prop: 'Remark', input: true },
  { label: '操作', width: 100 }
]);
const searchStatus = ref(true);
proxy.$formatKey(columns.value);
if (props.deviceColumns?.length) {
  searchStatus.value = false;
  columns.value = props.deviceColumns;
}
proxy.$formatKey(selectColumns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 10
});
const selectPage = ref({
  PageIndex: 1,
  PageSize: 10
});

const queryParams = ref({
  Code: '',
  Name: '',
  NoPage: '' //如果传"true"，则返回全部数据不分页
});
const fileList = ref([]);
const activeName = ref('first');
const queryRef = ref();
const show = ref(false);
const title = ref();
const formRef = ref();
const checkType = ref(1);
const rules = ref({
  Code: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  Name: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  Principal: [
    {
      required: true,
      message: '请选择',
      trigger: 'change'
    }
  ],
  ID_Area: [
    {
      required: true,
      message: '请选择',
      trigger: 'change'
    }
  ],
  ID_Place: [
    {
      required: true,
      message: '请选择',
      trigger: 'change'
    }
  ],
  Model: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  Manufacturer: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  ID_Type: [
    {
      required: true,
      message: '请选择',
      trigger: 'change'
    }
  ],
  Enable: [
    {
      required: true,
      message: '请选择',
      trigger: 'change'
    }
  ],
  State_Self: [
    {
      required: true,
      message: '请选择',
      trigger: 'change'
    }
  ],
  State: [
    {
      required: true,
      message: '请选择',
      trigger: 'change'
    }
  ],
  // Pictrues: [{ required: true, message: "请输入", trigger: "blur" }],
  FactoryTime: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ],
  FactoryTime: [
    {
      required: true,
      message: '请输入',
      trigger: 'blur'
    }
  ]
  //   Type: [{ required: true, message: "请选择", trigger: "change" }],
});

const formData = ref({});
const selectList = ref([]);
const bindDialog = ref(false);
const bindTitle = ref('');
const selectTotal = ref(0);
const showSelectList = ref([]);
const showDetail = ref(false);
const detailData = ref({});
const fileList2 = ref([]);
const maintainRow = ref({});

const selectDevice = ref([]);
const selectDeviceList = computed({
  get: () => {
    return props.checkList;
  },
  set: v => {
    selectDevice.value = v;
    emit('update:checkList', v);
  }
});

onMounted(() => {
  getList();
});
const Category = {
  1: '教学装备',
  2: '工具物资'
};
const State_Self = {
  1: '正常',
  2: '降级',
  3: '报废'
};
const State_SelfType = {
  1: 'success',
  2: 'danger',
  3: 'info'
};
const State = {
  1: props.Category == 1 ? '正常运行' : '在库',
  2: props.Category == 1 ? '保养中' : '检验中',
  3: '维修中',
  4: '使用中'
};
const StateType = {
  1: 'success',
  2: 'warning',
  3: 'danger',
  4: ''
};
async function getList() {
  try {
    show.value = false;
    let query = {
      ...queryParams.value,
      ...page.value,
      Category: props.Category
    };

    let res = await GetDeviceList_Page(query);
    res.data.List?.forEach(item => {
      item.State_SelfName = [
        {
          type: State_SelfType[item.State_Self],
          name: State_Self[item.State_Self]
        }
      ];
      item.StateName = [
        {
          type: StateType[item.State],
          name: State[item.State]
        }
      ];
    });
    tableList.value = res.data.List;
    Total.value = res.data.Total;
    selectList.value = tableList.Items;
  } catch (error) {
    console.log(error);
  }
}

async function handleDetail(row) {
  try {
    let res = await GetDeviceDetail({
      ID: row.ID
    });
    detailData.value = res.data;
    showDetail.value = true;
  } catch (error) {
    console.log(error);
  }
}

function getImgItem(item) {
  formData.value.ShowPictrue = item.removeHeadUrl;
  proxy.$modal.msgSuccess('选择成功');
}

function bindExecution(title) {
  bindTitle.value = title;
  bindDialog.value = true;
}

function addTableData(index) {
  outCheckList.value.splice(index + 1, 0, {
    Code: '',
    Content: ''
  });
}

async function confirm(val) {
  try {
    if (val) {
      let res;
      let query = {
        ...formData.value,
        Category: props.Category,
        Pictrues: fileList.value?.map(item => {
          return {
            FileID: item.ID,
            Sort: item.Sort
          };
        }),
        Files: fileList2.value?.map(item => {
          return {
            FileID: item.ID,
            Sort: item.Sort,
            Remark: item.Remark
          };
        })
      };

      if (formData.value.ID) {
        await EditDevice(query);
      } else {
        query.State = 1;
        res = await AddDevice(query);
      }
      let bindQuery;
      if (checkType.value == 1) {
        bindQuery = {
          DeviceID: formData.value.ID ? formData.value.ID : res.data,
          MaintainPlans: showSelectList.value?.map(item => {
            return {
              ID_MaintainPlan: item.ID, //保养方案ID
              Interval: item.Interval, //保养间隔（小时）
              LastMaintainTime: item.LastMaintainTime, //最后一次保养时间
              Remark: item.Remark, //备注
              Principal: item.Principal, //负责人 用户ID
              Type: checkType.value //方式 1:内部 2:外部(方案ID传0)
            };
          })
        };
      } else {
        bindQuery = {
          DeviceID: formData.value.ID ? formData.value.ID : res.data,
          MaintainPlans: outCheckList.value?.map(item => {
            return {
              ID_MaintainPlan: 0, //保养方案ID
              Interval: item.Interval, //保养间隔（小时）
              LastMaintainTime: item.LastMaintainTime, //最后一次保养时间
              Remark: item.Remark, //备注
              Principal: item.Principal, //负责人 用户ID
              Type: checkType.value //方式 1:内部 2:外部(方案ID传0)
            };
          })
        };
      }

      await DeviceBindMaintainPlan(bindQuery);
      if (formData.value.ID) {
        proxy.$modal.msgSuccess('修改成功');
      } else {
        proxy.$modal.msgSuccess('添加成功');
      }
      getList();
    }
  } catch (error) {
    console.log(error);
  }
}

function deleteTableData(index) {
  outCheckList.value.splice(index, 1);
}

function subConfirm() {
  // selectTotal.value = selectList.value.length;
  selectList.value?.forEach(item => {
    if (!item.Interval && !item.LastMaintainTime && !item.Principal) {
      item.Remark = '';
    }
  });
  showSelectList.value = selectList.value;
  bindDialog.value = false;
}

function selectDelete(row) {
  selectList.value = selectList.value?.filter(item => item.ID != row.ID);
  showSelectList.value = showSelectList.value?.filter(
    item => item.ID != row.ID
  );
}

async function handleEdit(row) {
  try {
    let { data } = await GetDeviceDetail({
      ID: row.ID
    });
    activeName.value = 'first';
    formData.value = {
      ...data.Info
    };
    data.Maintain?.forEach(item => {
      item.ID = item.ID_MaintainPlan;
      item.Code = item.Code_MaintainPlan;
      item.Name = item.Name_MaintainPlan;
    });
    fileList.value = data.Info.Pictrues;
    fileList.value?.forEach(item => (item.ID = item.FileID));
    fileList2.value = data.Info.Files;
    fileList2.value?.forEach(item => (item.ID = item.FileID));

    title.value = `修改${props.Label}`;
    checkType.value = data.Maintain?.[0]?.['Type'] || 1;
    if (checkType.value == 1) {
      showSelectList.value = data.Maintain;
      selectList.value = data.Maintain;
      outCheckList.value = [{}];
    } else {
      outCheckList.value = data.Maintain || [{}];
      showSelectList.value = [];
      selectList.value = [];
    }
    if (!data.Maintain?.length) {
      outCheckList.value = [{}];
    }
    console.log(outCheckList.value);
    show.value = true;
  } catch (error) {
    console.log(error);
  }
}
async function handleDelete(row) {
  try {
    await DelDevice({ ID: row.ID });
    proxy.$modal.msgSuccess('删除成功');
    getList();
  } catch (error) {
    console.log(error);
  }
}

function checkTypeChange(val) {
  // if (val == 2 && !showSelectList.value.length) {
  //   showSelectList.value.push({
  //     Interval: 0,
  //     LastMaintainTime: "",
  //     Remark: "",
  //     Principal: "",
  //   });
  // } else {
  // selectList.value = [];
  // showSelectList.value = [];
  // }
}

function handleAdd() {
  formData.value = {};
  showSelectList.value = [];
  selectList.value = [];
  fileList2.value = [];
  fileList.value = [];
  activeName.value = 'first';
  outCheckList.value = [{}];
  title.value = `添加${props.Label}`;

  show.value = true;
}
function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
function resetQuery() {
  queryParams.value = {
    Code: '',
    Name: '',
    NoPage: ''
  };
  handleQuery();
}
</script>

<style lang="scss" scoped>
.selectBox {
  display: flex;
  border: 1px solid #ddd;
  margin-bottom: 10px;

  .selectItem {
    padding: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
